import React from 'react';
import { Button, Drawer, Form, message, Modal, Skeleton, Space, Spin } from 'antd';
import { Chat, ChatMessage } from 'components/Chat';
import { CallSummaryDetail } from 'admin/schema/Task';
import { getCallStatusName } from 'admin/pages/Task/components/TaskTool';

import { addPhoneInBlack, queryPhoneInBlack, removePhoneInBlack } from 'admin/servers/servers';

import './style.scss';

interface IProp {
  /**从列表获取-请求数据接口 */
  fetchRecord: (params: any) => Promise<any>;
  refreshRecordHistory?: () => Promise<any>;
  showRefresh?: boolean; // 展示刷新按钮
}
interface IState {
  /** 行数据 */
  record: any;
  /**显示隐藏 */
  visible: boolean;
  /**列表查询条件 */
  searchParms: any;
  /**当前页码 */
  pageNum: number;
  /**总页码 */
  pageTotal: number;
  /**通话详情 */
  detailInfo: any;
  /**通话小结 */
  callSummary?: CallSummaryDetail;
  /**是否已加入黑名单 */
  isBlack: boolean;
  /***加载数据 */
  loading: boolean;
}

interface IRecordInfo {
  /**序号 */
  index: number;
  role: number;
  text: string;
  time: string;
  url: string;
  status: number;
}
/**通用控件-通话详情-弹窗 */
export class CallRecordDetailDrawer extends React.Component<IProp, IState> {
  private chatRef: React.RefObject<any>;

  constructor(prop: IProp) {
    super(prop);
    this.chatRef = React.createRef();
    this.state = {
      record: {},
      visible: false,
      detailInfo: {},
      callSummary: undefined,
      isBlack: false,
      searchParms: {},
      pageNum: 0,
      pageTotal: 0,
      loading: false,
    };
  }
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }
  /**
   * 展开抽屉控件
   * rowRecord 直接传递列表行数据，防止数据库数据变更引起行数不一致问题
   */
  public show(searchParms: any, rowRecord?: any) {
    this.setState(
      {
        record: rowRecord,
        visible: true,
        searchParms,
        pageNum: searchParms.pageNo,
      },
      () => {
        rowRecord ? this.initData(rowRecord, searchParms, searchParms.pageTotal) : this.fetchList();
      }
    );
  }

  /**
   * 隐藏控件
   */
  public hide() {
    this.setState({
      visible: false,
      detailInfo: {},
      callSummary: {} as CallSummaryDetail,
    });
  }

  /**
   * 将后端返回的数据处理为Chat控件所需要的数据
   */
  private dataHandler(listInfo: IRecordInfo[]): ChatMessage[] {
    const roleMap = ['called', 'caller', 'man'];
    return listInfo.map((item, i) => {
      return {
        index: item.index,
        sound: item.url,
        message: item.text,
        role: roleMap[item.role] as 'called' | 'caller' | 'man',
        status: item.status,
      };
    });
  }
  /**
   * 查询号码是否已加入黑名单
   */
  async checkPhoneInBlack(callRecordId: string) {
    try {
      const res = await queryPhoneInBlack({ callRecordId });
      const { data } = res;
      this.setState({
        isBlack: data.isBlacklist,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }

  /**
   * 操作：加入/移除-黑名单
   * 0-移出
   * 1-添加
   */
  async changePhoneInBlack(callRecordId: string, type: 0 | 1) {
    try {
      if (type) {
        await addPhoneInBlack({ callRecordId });
        message.success('号码已加入黑名单');
        this.setState({
          isBlack: true,
        });
      } else {
        await removePhoneInBlack({ callRecordId });
        message.success('号码已从黑名单移除');
        this.setState({
          isBlack: false,
        });
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }
  /**上一条 */
  prev() {
    const { pageNum } = this.state;
    this.setState(
      {
        pageNum: pageNum - 1,
      },
      () => {
        this.fetchList();
      }
    );
  }
  /**下一条 */
  next() {
    const { pageNum } = this.state;
    this.setState(
      {
        pageNum: pageNum + 1,
      },
      () => {
        this.fetchList();
      }
    );
  }
  /**详情数据上屏展示 */
  initData(record: any, searchParms: any, pageTotal = 0) {
    this.checkPhoneInBlack(record.callRecordId);
    this.setState(
      {
        detailInfo: record,
        callSummary: record.callsummary as CallSummaryDetail,
        // 查询条件
        searchParms,
        // 当前页码
        pageNum: searchParms.pageNo || 0,
        // 总页码
        pageTotal,
      },
      () => {
        // console.log('record.soundRecord.recordList', record.soundRecord.recordList);
        // 展示通话聊天记录
        setTimeout(() => {
          record.soundRecord &&
            this.chatRef.current?.setRecord(
              this.dataHandler(record.soundRecord.recordList).reverse()
            );
        }, 200);
      }
    );
  }

  // 新查询会话历史记录（刷新加载全部历史聊天，修复不全聊天记录）
  refreshRecordHistory = async () => {
    this.setState({
      loading: true,
    });

    await this.props.refreshRecordHistory?.();

    this.setState({
      loading: false,
    });
  };

  /**
   * 查询页面数据(上一条，下一条)
   */
  private async fetchList() {
    this.setState({
      loading: true,
    });
    const { pageNum, searchParms } = this.state;
    // 更新页码
    searchParms.pageNo = pageNum;
    delete searchParms.pageTotal;
    console.log(searchParms, '++++翻页查询条件');
    try {
      const res = await this.props.fetchRecord(searchParms);
      const record = res.data[0];
      const pageTotal = res.count || 0;
      this.initData(record, searchParms, pageTotal);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      loading: false,
    });
  }
  render() {
    const { visible, detailInfo, callSummary, isBlack, pageNum, pageTotal, loading } = this.state;
    const { callRecordId, flowType, taskType } = detailInfo;
    const { chatRef } = this;
    const layout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };
    return (
      <Drawer
        className="callrecord-detail"
        key={callRecordId}
        title="通话记录详情"
        width={900}
        visible={visible}
        destroyOnClose={true}
        onClose={this.hide.bind(this)}
        footer={
          <Space>
            <Button
              size="small"
              type="primary"
              onClick={this.prev.bind(this)}
              disabled={pageNum === 1 ? true : false}
            >
              上一条
            </Button>
            <Button
              size="small"
              type="primary"
              ghost
              onClick={this.next.bind(this)}
              disabled={pageNum === pageTotal ? true : false}
            >
              下一条
            </Button>
          </Space>
        }
      >
        <Spin spinning={loading} size="large" tip="加载中">
          <div className="callrecord-info">
            <div className="title">
              <span>基本资料</span>
              <Button
                size="small"
                type="primary"
                onClick={() => {
                  Modal.confirm({
                    title: isBlack ? '移除黑名单' : '加入黑名单',
                    content: isBlack ? '确定将该号码移除黑名单吗？' : '确定将该号码加入黑名单吗？',
                    onOk: () => {
                      this.changePhoneInBlack(detailInfo.callRecordId, isBlack ? 0 : 1);
                    },
                  });
                }}
              >
                {isBlack ? '移除黑名单' : '加入黑名单'}
              </Button>
            </div>
            <Skeleton loading={loading}>
              <Form layout="horizontal" {...layout} colon={false}>
                <Form.Item label="流水号">{detailInfo.callRecordId || '--'}</Form.Item>
                <Form.Item label="任务名称">{detailInfo.taskName || '--'}</Form.Item>
                <Form.Item label="主叫号码">{detailInfo.callerNumber || '--'}</Form.Item>
                <Form.Item label="被叫号码">{detailInfo.calledNumber || '--'}</Form.Item>
                <Form.Item label="被叫姓名">{detailInfo.calledName || '--'}</Form.Item>
                <Form.Item label="被叫备注">{detailInfo.calledRemark || '--'}</Form.Item>
                <Form.Item label="用户意向">{detailInfo.userIntention || '--'}</Form.Item>
                <Form.Item label="执行次数">
                  {detailInfo.callRound >= 0 ? detailInfo.callRound : '--'}
                </Form.Item>
                <Form.Item label="开始时间">{detailInfo.callBeginTime || '--'}</Form.Item>
                <Form.Item label="结束时间">{detailInfo.callEndTime || '--'}</Form.Item>
                <Form.Item label="通话时长">
                  {detailInfo.callTalkTime >= 0 ? detailInfo.callTalkTime : '--'}
                </Form.Item>
                <Form.Item label="呼叫状态">
                  {getCallStatusName(detailInfo.callStatus) || '--'}
                </Form.Item>
                <Form.Item label="机器人标识">{detailInfo.nluId || '--'}</Form.Item>
              </Form>
              {/* 坐席端:taskType-2：人机协同，3：人工自动外呼 */}
              {(flowType === 3 || taskType === 3) && callSummary && (
                <>
                  <div className="title">小结信息</div>
                  <Form layout="horizontal" {...layout} colon={false}>
                    <Form.Item label="成访结果">
                      {callSummary.visitResult
                        ? '成功'
                        : callSummary.visitResult == null
                        ? '--'
                        : '失败'}
                    </Form.Item>
                    <Form.Item label="营销结果">
                      {callSummary.marketingResult
                        ? '成功'
                        : callSummary.marketingResult == null
                        ? '--'
                        : '失败'}
                    </Form.Item>
                    <Form.Item label="备注">{callSummary.remarks || '--'}</Form.Item>
                  </Form>
                </>
              )}
            </Skeleton>
          </div>
          <div className="callrecord-chat">
            <div
              className="callrecord-chat-title"
              style={{
                marginBottom: 10,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
              }}
            >
              <div>通话记录</div>
              {this.props.showRefresh && <div onClick={this.refreshRecordHistory}>刷新</div>}
            </div>
            <Skeleton loading={loading} avatar>
              <Chat
                showHeadBar={true}
                talkRecord={
                  detailInfo.soundRecord
                    ? (process.env.REACT_APP_API_URL || '') + detailInfo.soundRecord.url
                    : ''
                }
                callRecordId={callRecordId}
                showStatusHeader={false}
                ref={chatRef}
              />
            </Skeleton>
          </div>
        </Spin>
      </Drawer>
    );
  }
}
